package com.leessy.r229.kt

import android.view.View
/***
 * 点击事件的View扩展
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
fun <T : View> T.onClick(block: (T) -> Unit) = setOnClickListener {
    block(it as T)
}


/***
 * 带延迟过滤的点击事件View扩展
 * @param delay Long 延迟时间，默认600毫秒
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
fun <T : View> T.clickThrottleFirst(time: Long = 600, block: (T) -> Unit) {
    triggerDelay = time
    setOnClickListener {
        if (clickEnable()) {
            block(it as T)
        }
    }
}

/***
 * 设置延迟时间的View扩展
 * @param delay Long 延迟时间，默认600毫秒
 * @return T
 */
fun <T : View> T.clickWithTriggerDelay(delay: Long = 600): T {
    triggerDelay = delay
    return this
}

private var <T : View> T.triggerDelay: Long
    get() = if (getTag(1123461123) != null) getTag(1123461123) as Long else 600
    set(value) {
        setTag(1123461123, value)
    }

private var <T : View> T.triggerLastTime: Long
    get() = if (getTag(1123460103) != null) getTag(1123460103) as Long else -601
    set(value) {
        setTag(1123460103, value)
    }

private fun <T : View> T.clickEnable(): Boolean {
    var flag = false
    val currentClickTime = System.currentTimeMillis()
    if (currentClickTime - triggerLastTime >= triggerDelay) {
        flag = true
    }
    triggerLastTime = currentClickTime
    return flag
}

fun <T : View> T.visible() {
    visibility = View.VISIBLE
}

fun <T : View> T.invisible() {
    visibility = View.INVISIBLE
}

fun <T : View> T.gone() {
    visibility = View.GONE
}

///**
// * 多次点击最多只有一个执行
// */
//fun View.onClickMostOne(action: suspend (v: View) -> Unit) {
//    // launch one actor to handle all events on this node
//    val eventActor = GlobalScope.actor<View>(Dispatchers.Main) {
//        for (event in channel) action(event) // pass event to action
//
//    }
//
//    // install a listener to activate this actor
//    setOnClickListener {
//        eventActor.offer(it)
//    }
//    // install a listener to offer events to this actor
////    onMouseClicked = EventHandler { event ->
////        eventActor.offer(event)
////    }
//}
